package com.ls.fw.token.support;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * A {@link TokenRepository} that stores the {@link Token} in the
 * {@link HttpSession}.
 */
public final class HttpSessionTokenRepository implements TokenRepository {
	
	private static final String DEFAULT_TOKEN_ATTR_NAME = HttpSessionTokenRepository.class
			.getName().concat(DEFAULT_PARAMETER_NAME).concat(".TOKEN");

	protected Logger logger = LoggerFactory.getLogger(getClass());
    
	private String parameterName = DEFAULT_PARAMETER_NAME;

	private String headerName = DEFAULT_HEADER_NAME;

	private String sessionAttributeName = DEFAULT_TOKEN_ATTR_NAME;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 *com.ls.fw.token.support.TokenRepository#saveToken(org.springframework
	 * .security.web.csrf.Token, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	public void saveToken(Token token, HttpServletRequest request,
			HttpServletResponse response) {
		if (token == null) {
			HttpSession session = request.getSession(false);
			if (session != null) {
				session.removeAttribute(this.getKey(request));
			}
		}
		else {
			HttpSession session = request.getSession();
			session.setAttribute(this.getKey(request), token);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 *com.ls.fw.token.support.TokenRepository#loadToken(javax.servlet
	 * .http.HttpServletRequest)
	 */
	public Token loadToken(HttpServletRequest request,boolean createIFNoExist) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			logger.warn("session 为空！");
			return null;
		}
		Token token = (Token) session.getAttribute(this.getKey(request));
		if(token == null && createIFNoExist){
			token = this.generateToken(request);
			this.saveToken(token, request, null);
		}
		if(token == null){
			logger.warn("session 中token 为空！");
		}
		return token;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 *com.ls.fw.token.support.TokenRepository#generateToken(javax.servlet
	 * .http.HttpServletRequest)
	 */
	public Token generateToken(HttpServletRequest request) {
		return new DefaultToken(this.getHeaderName(), this.getParameterName(), createNewToken());
	}

	/**
	 * Sets the {@link HttpServletRequest} parameter name that the {@link Token} is
	 * expected to appear on
	 * @param parameterName the new parameter name to use
	 */
	public void setParameterName(String parameterName) {
		Assert.hasLength(parameterName, "parameterName cannot be null or empty");
		this.parameterName = parameterName;
	}

	/**
	 * Sets the header name that the {@link Token} is expected to appear on and the
	 * header that the response will contain the {@link Token}.
	 *
	 * @param headerName the new header name to use
	 */
	public void setHeaderName(String headerName) {
		Assert.hasLength(headerName, "headerName cannot be null or empty");
		this.headerName = headerName;
	}

	/**
	 * Sets the {@link HttpSession} attribute name that the {@link Token} is stored in
	 * @param sessionAttributeName the new attribute name to use
	 */
	public void setSessionAttributeName(String sessionAttributeName) {
		Assert.hasLength(sessionAttributeName,
				"sessionAttributename cannot be null or empty");
		this.sessionAttributeName = sessionAttributeName;
	}

	private String createNewToken() {
		return UUID.randomUUID().toString();
	}

	@Override
	public void removeToken(Token token, HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.removeAttribute(this.getKey(request));
		}
	}

	@Override
	public String getKey(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return sessionAttributeName+session.getId();
	}

	@Override
	public String getHeaderName() {
		return this.headerName;
	}

	@Override
	public String getParameterName() {
		return this.parameterName;
	}
}
